//
//  NetWorkTools.swift
//  Weibo
//
//  Created by 付启刚 on 15/12/23.
//  Copyright © 2015年 faq. All rights reserved.
//

import AFNetworking
let dataErrorDomain="com.faq.data.error"
//枚举任意类型
enum HTTPMethod:String{
    case GET = "GET"
    case POST = "POST"
}
class NetWorkTools: AFHTTPSessionManager {
    static let sharedTools : NetWorkTools = {
    //设置base Url
        let urlString="https://api.weibo.com/"
        let url=NSURL(string: urlString)
        let tools=NetWorkTools(baseURL: url)
        tools.responseSerializer.acceptableContentTypes?.insert("text/plain")
        return tools
    }()
    //网络请求核心方法封装
    func requestJSONDict(method:HTTPMethod,urlString:String,parameters:[String:String]?,finished:(dict:[String:AnyObject]?,error:NSError?)->()){
        if method==HTTPMethod.POST{
            //发送POST请求
            POST(urlString, parameters: parameters, progress: { (p) -> Void in
                print(p)
                }, success: { (_, result) -> Void in
                    //请求成功的回调
                    //print(result)
                    guard let dict=result as? [String:AnyObject] else{
                        //不能转换为字典
                        //执行失败的回调
                        //domain:反转域名 com.baidu.error
                        //                    code:错误状态码 自定义错误信息 一般使用负数
                        //userInfo:错误描述信息
                        let myError=NSError(domain: dataErrorDomain, code: -10000, userInfo: [NSLocalizedDescriptionKey:"数据不合法"])
                        print(myError)
                        finished(dict: nil, error: myError)
                        return
                    }
                    //执行成功的回调
                    finished(dict: dict, error: nil)
                    
                }) { (_, error) -> Void in
                    //失败的回调
                    finished(dict: nil, error: error)
                    print(error)
            }

        }else{
                GET(urlString, parameters: parameters, progress: { (p) -> Void in
            print(p)
            }, success: { (_, result) -> Void in
               //print(result)
                guard let dict=result as? [String:AnyObject] else{
                    //不能转换为字典
                    //执行失败的回调
                    //domain:反转域名 com.baidu.error
                    //                    code:错误状态码 自定义错误信息 一般使用负数
                    //userInfo:错误描述信息
                    let myError=NSError(domain: dataErrorDomain, code: -10000, userInfo: [NSLocalizedDescriptionKey:"数据不合法"])
                    print(myError)
                    finished(dict: nil, error: myError)
                    return
                }
                //执行成功的回调
                finished(dict: dict, error: nil)
            }) { (_, error) -> Void in
                //失败的回调
                finished(dict: nil, error: error)
                print(error)
           }
        }
    }
}
